package com.beingmate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.org.mozilla.javascript.internal.json.JsonParser;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println(request.getParameter("username"));
		System.out.println(request.getParameter("email"));
		PrintWriter out = response.getWriter();
		//out.write(request.getParameter("username"));
		request.getRequestDispatcher("/grid.html").forward(request, response);
		//response.sendRedirect("/grid.html");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		response.setContentType("application/json; charset=utf-8"); 
		response.setHeader("Cache-Control", "no-cache"); 
		PrintWriter out = response.getWriter();
		boolean  isExit = false;
		ReadXMLUtil util = new ReadXMLUtil();
		List<User> list = util.readXml("\\work\\workspace\\demo\\src\\com\\beingmate\\user.xml");
		for(User user : list){
			if(username.equals(user.getUsername()) && password.equals(user.getPassword())){
				isExit = true;
				break;
			}
		}
		String str = "{\"msg\":\"error login\",\"status\":\"false\"}"; 
		if(isExit){
			str = "{\"msg\":\"success login\",\"status\":\"true\"}"; 
		}
		out.print(str); 
		out.flush(); 
		out.close();
	}

}
